package com.chenjun.request;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;

import com.chenjun.utils.StreamUtils;
import com.chenjun.utils.StringUtils;

/**
 * 封装常见的Get And Post方法,并且用自己写的工具类来输出相应字符串，并且关闭流
 * 
 * @author Administrator
 * 
 */
public class HttpClientMethod
{
	private String urlPath;
	private int timeOutValue = 5000; // 超时参数

	/**
	 * 发送GET请求。URL参数可以自己拼接
	 * 
	 * @param urlPath
	 * @return
	 */
	public String httpGetMethod(String urlPath)
	{
		urlPath = StringUtils.replaceSpecialChar(urlPath);
		System.out.println("access url ----------------->"+urlPath);
		String result = null;
		HttpEntity httpEntity = null;
		InputStream inputStream = null;
		HttpClient httpClient = HttpClients.createDefault();
		HttpGet httpGet = new HttpGet(urlPath);
		HttpResponse response = null;
		// 下面两行仅支持4.3以上版本
		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeOutValue).setConnectTimeout(timeOutValue).build();// 设置请求和传输超时时间
		httpGet.setConfig(requestConfig);
		try
		{
			response = httpClient.execute(httpGet);
		}
		catch (ClientProtocolException e)
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
		{
			httpEntity = response.getEntity();
		}
		if (httpEntity != null)
		{
			try
			{
				inputStream = httpEntity.getContent();
			}
			catch (UnsupportedOperationException e)
			{
				e.printStackTrace();
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
			finally
			{
				// 流的关闭操作已经在converStreamToString（）处理了
				result = StreamUtils.converStreamToString(inputStream);
			}
		}
		return result;
	}

	/**
	 * 发送带参数的POST请求
	 * 
	 * @param urlPath
	 * @param paramsMap
	 * @return
	 */
	public String httpPostMethod(String urlPath, Map<String, String> paramsMap)
	{
		HttpClient httpClient = HttpClients.createDefault();
		httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000);
		HttpPost httpPost = new HttpPost(urlPath);
		HttpResponse httpResponse = null;
		HttpEntity httpEntity = null;
		InputStream inputStream = null;
		String result = null;
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(0);
		// 当map不为空时，遍历map，取出键值对
		if (paramsMap != null)
		{
			for (Map.Entry<String, String> entry : paramsMap.entrySet()) // 遍历Map
			{
				nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
			}
		}
		try
		{
			httpEntity = new UrlEncodedFormEntity(nameValuePairs, "UTF-8");
		}
		catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
		}
		httpPost.setEntity(httpEntity);
		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeOutValue).setConnectTimeout(timeOutValue).build();// 设置请求和传输超时时间
		httpPost.setConfig(requestConfig);
		try
		{
			httpResponse = httpClient.execute(httpPost);
		}
		catch (ClientProtocolException e)
		{
			System.err.println(urlPath+"协议错误");
			e.printStackTrace();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
		{
			try
			{
				inputStream = httpResponse.getEntity().getContent();
			}
			catch (UnsupportedOperationException e)
			{
				e.printStackTrace();
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
			finally
			{
				// 流的关闭操作已经在converStreamToString（）处理了
			}
		}
		result = StreamUtils.converStreamToString(inputStream);
		return result;
	}

	/**
	 * 重载HttpPostMethod，不带参数的POST请求
	 * 
	 * @param urlPath
	 * @return
	 */
	public String httpPostMethod(String urlPath)
	{
		HttpClient httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(urlPath);
		HttpResponse httpResponse = null;
		HttpEntity httpEntity = null;
		InputStream inputStream = null;
		String result = null;
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(0);
		try
		{
			httpEntity = new UrlEncodedFormEntity(nameValuePairs, "UTF-8");
		}
		catch (UnsupportedEncodingException e1)
		{
			e1.printStackTrace();
		}
		httpPost.setEntity(httpEntity);
		RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeOutValue).setConnectTimeout(timeOutValue).build();// 设置请求和传输超时时间
		httpPost.setConfig(requestConfig);
		try
		{
			httpResponse = httpClient.execute(httpPost);
		}
		catch (ClientProtocolException e)
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
		{
			try
			{
				inputStream = httpResponse.getEntity().getContent();
			}
			catch (UnsupportedOperationException e)
			{
				e.printStackTrace();
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
			finally
			{
				// 流的关闭操作已经在converStreamToString（）处理了
			}
		}
		result = StreamUtils.converStreamToString(inputStream);
		return result;
	}

	public static void main(String[] args)
	{
		HttpClientMethod httpClientMethod = new HttpClientMethod();
		// System.out.println(httpClientMethod.httpGetMethod(URLPath));

		// System.out.println(httpClientMethod.httpPostMethod(urlPath));
	}

	public String getUrlPath()
	{
		return urlPath;
	}

	public void setUrlPath(String urlPath)
	{
		this.urlPath = urlPath;
	}

	public long getTimeOutValue()
	{
		return timeOutValue;
	}

	public void setTimeOutValue(int timeOutValue)
	{
		this.timeOutValue = timeOutValue;
	}

}
